package vip.liux.contracts.infrastructure.pay.dto.refund;

import lombok.Data;
import vip.liux.contracts.infrastructure.pay.PayClientException;
import vip.liux.contracts.shared.enums.pay.PayRefundStatus;

import java.time.LocalDateTime;

/**
 * 渠道退款订单 Response Dto
 *
 * @author jason
 */
@Data
public class ClientPayRefundDto {

    /**
     * 退款状态
     * <p>
     * 枚举 {@link PayRefundStatus}
     */
    private Integer status;

    /**
     * 外部退款号
     * <p>
     * 对应 PayRefundDO 的 no 字段
     */
    private String outRefundNo;

    /**
     * 渠道退款单号
     * <p>
     * 对应 PayRefundDO.channelRefundNo 字段
     */
    private String channelRefundNo;

    /**
     * 退款成功时间
     */
    private LocalDateTime successTime;

    /**
     * 原始的异步通知结果
     */
    private Object rawData;

    /**
     * 调用渠道的错误码
     * <p>
     * 注意：这里返回的是业务异常，而是不系统异常。
     * 如果是系统异常，则会抛出 {@link PayClientException}
     */
    private String channelErrorCode;
    /**
     * 调用渠道报错时，错误信息
     */
    private String channelErrorMsg;

    private ClientPayRefundDto() {
    }

    /**
     * 创建【WAITING】状态的退款返回
     */
    public static ClientPayRefundDto waitingOf(String channelRefundNo,
                                               String outRefundNo, Object rawData) {
        ClientPayRefundDto respDto = new ClientPayRefundDto();
        respDto.status = PayRefundStatus.WAITING.getValue();
        respDto.channelRefundNo = channelRefundNo;
        // 相对通用的字段
        respDto.outRefundNo = outRefundNo;
        respDto.rawData = rawData;
        return respDto;
    }

    /**
     * 创建【SUCCESS】状态的退款返回
     */
    public static ClientPayRefundDto successOf(String channelRefundNo, LocalDateTime successTime,
                                               String outRefundNo, Object rawData) {
        ClientPayRefundDto respDto = new ClientPayRefundDto();
        respDto.status = PayRefundStatus.SUCCESS.getValue();
        respDto.channelRefundNo = channelRefundNo;
        respDto.successTime = successTime;
        // 相对通用的字段
        respDto.outRefundNo = outRefundNo;
        respDto.rawData = rawData;
        return respDto;
    }

    /**
     * 创建【FAILURE】状态的退款返回
     */
    public static ClientPayRefundDto failureOf(String outRefundNo, Object rawData) {
        return failureOf(null, null,
                outRefundNo, rawData);
    }

    /**
     * 创建【FAILURE】状态的退款返回
     */
    public static ClientPayRefundDto failureOf(String channelErrorCode, String channelErrorMsg,
                                               String outRefundNo, Object rawData) {
        ClientPayRefundDto respDto = new ClientPayRefundDto();
        respDto.status = PayRefundStatus.FAILURE.getValue();
        respDto.channelErrorCode = channelErrorCode;
        respDto.channelErrorMsg = channelErrorMsg;
        // 相对通用的字段
        respDto.outRefundNo = outRefundNo;
        respDto.rawData = rawData;
        return respDto;
    }

}
